<template>
  <div>
    <el-dialog
      v-model="dialogVisible"
      width="80%"
      align-center
      :show-close="false"
      destroy-on-close
      draggable
      @open="handleOpen"
      @close="handleClose"
    >
      <template #header="{ close }">
        <div class="dialog-header flex justify-between items-center">
          <div>项目变更</div>
          <el-icon class="el-icon--left cursor-pointer" @click="close"
            ><CircleCloseFilled color="#fff"
          /></el-icon>
        </div>
      </template>
      <ProjectInfo :projectId="projectId" />
      <div class="bg-white my-[10px]">
        <BaseHead>请选择变更类型</BaseHead>
        <div class="p-[10px]">
          <el-checkbox-group v-model="changeType" @change="typeChange">
            <el-checkbox
              :label="item.name"
              :value="item.code"
              v-for="item in changeTypeList.value"
              :key="item.id"
              :disabled="item.disabled"
            />
          </el-checkbox-group>
        </div>
      </div>
      <el-form :model="editForm" :rules="rules" ref="editFormRef">
        <!-- 负责人变更 -->
        <div class="bg-white mt-[10px]" v-if="changeType.includes('chargerName')">
          <BaseHead>负责人变更</BaseHead>
          <BaseTable>
            <tr>
              <td class="td-name">变更后负责人<span class="no-empty">*</span></td>
              <td style="width: 87.5%" colspan="3">
                <el-form-item label="" prop="changeChargerName">
                  <el-autocomplete
                    v-model="editForm.changeChargerName"
                    :fetch-suggestions="queryChargerPerosn"
                    clearable
                    placeholder="请输入检索关键词"
                    value-key="name"
                    highlight-first-item
                    @select="selectChargerPerosn"
                    @blur="chargerPerosnBlur"
                  >
                    <template #default="{ item }">
                      <span>{{ item.name }}</span>
                      <span class="mx-[10px]">{{ item.account }}</span>
                      <span>{{ item.unitName }}</span>
                    </template>
                  </el-autocomplete>
                </el-form-item>
              </td>
            </tr>
          </BaseTable>
        </div>
        <!-- 合同经费变更 -->
        <div class="bg-white mt-[10px]" v-if="changeType.includes('feeAuthorize')">
          <BaseHead>合同经费变更</BaseHead>
          <BaseTable>
            <tr>
              <td class="td-name">变更后合同经费（万元）<span class="no-empty">*</span></td>
              <td style="width: 87.5%" colspan="3">
                <el-form-item label="" prop="changeFeeAuthorize">
                  <el-input
                    v-model="editForm.changeFeeAuthorize"
                    clearable
                    @input="fomateNumber(editForm, 'changeFeeAuthorize', $event)"
                    style="width: 300px"
                  />
                </el-form-item>
              </td>
            </tr>
          </BaseTable>
        </div>
        <!-- 延期变更 -->
        <div class="bg-white mt-[10px]" v-if="changeType.includes('delayFinish')">
          <BaseHead>延期变更</BaseHead>
          <BaseTable>
            <tr>
              <td class="td-name">延期结项至<span class="no-empty">*</span></td>
              <td style="width: 87.5%" colspan="3">
                <el-form-item label="" prop="changePlanEndDate">
                  <el-date-picker
                    v-model="editForm.changePlanEndDate"
                    type="date"
                    clearable
                    value-format="YYYY-MM-DD"
                    style="width: 240px"
                  />
                </el-form-item>
              </td>
            </tr>
          </BaseTable>
        </div>
        <div class="bg-white">
          <BaseTable>
            <tr>
              <td class="td-name">变更证明材料</td>
              <td style="width: 87.5%">
                <FileUpload
                  :uploadUrl="uploadUrl"
                  v-model="fileList"
                  tip=""
                  :limit="1"
                  @change="fileChange"
                />
              </td>
            </tr>
            <tr>
              <td class="td-name">变更原因<span class="no-empty">*</span></td>
              <td>
                <el-form-item label="" prop="alterReason" class="mb-[0px]">
                  <el-input
                    v-model="editForm.alterReason"
                    placeholder="变更原因"
                    type="textarea"
                    show-word-limit
                    maxlength="500"
                  />
                </el-form-item>
              </td>
            </tr>
          </BaseTable>
        </div>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <div class="operate-btns">
            <!-- <template v-if="verifyRoleType.isKyry()">
              <el-button type="primary" @click="save(-1)" :loading="loading">暂存</el-button>
              <el-button type="primary" @click="save(1)" :loading="loading">提交</el-button>
            </template>
            <template v-if="verifyRoleType.iskycgly()">
              <el-button type="primary" @click="save(-1)" :loading="loading">保存</el-button>
              <el-button
                type="primary"
                @click="save(2)"
                v-if="[-1, 3].includes(Number(checkStatus)) || isAuditor"
                :loading="loading"
                >保存并通过</el-button
              >
            </template> -->
            <el-button
              type="primary"
              @click="save(-1)"
              :loading="loading && submitType == -1"
              :disabled="loading && submitType != -1"
              >{{ verifyRoleType.isKyry() ? "暂存" : "保存" }}</el-button
            >
            <el-button
              type="primary"
              @click="save(1)"
              :loading="loading && submitType == 1"
              :disabled="loading && submitType != 1"
              v-if="verifyRoleType.isKyry()"
              >提交</el-button
            >
            <el-button
              type="primary"
              @click="save(2)"
              v-if="
                verifyRoleType.iskycgly() && ([-1, 3].includes(Number(checkStatus)) || isAuditor)
              "
              :loading="loading && submitType == 2"
              :disabled="loading && submitType != 2"
              >保存并通过</el-button
            >
            <el-button type="primary" @click="dialogVisible = false">关闭</el-button>
          </div>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import BaseHead from "@/views/project/components/BaseHead.vue";
import BaseTable from "@/views/project/components/BaseTable.vue";
import FileUpload from "@/views/project/components/FileUpload.vue";
import ProjectInfo from "./ProjectInfo.vue";
import useCommonFetch from "@/hooks/useCommonFetch";
import { getPersonList } from "@/api/project/common";
import { ElMessage } from "element-plus";
import { recordsDetail, addRecords } from "@/api/project/zx/xmbg";
import { baseInfo } from "@/api/project/zx/lxxm";
import { assignObj } from "@/utils/main";
import { verifyRoleType, fomateNumber } from "@/utils/main";
const changeTypeList = ref([]);
const uploadUrl = `/commonFile/uploadFile?modelName=横向项目项目变更证明材料`;
const fileList = ref([]);
const projectId = ref(null);
const dialogVisible = ref(false);
const editFormRef = ref();
const changeType = ref([]); //选择的变更类型
const detailData = ref({});
const operateId = ref(null);
const isAuditor = ref(false);
const taskId = ref("");
const checkStatus = ref("");
const planEndDate = ref(); //计划结束日期
const chargerCode = ref(null); //负责人id
const feeAuthorize = ref(0); //合同经费
const loading = ref(false);
const submitType = ref(null);

//选择的变更类型名称
const changeTypeName = computed(() => {
  const typeName = [];
  changeType.value.forEach((code) => {
    changeTypeList.value.value.forEach((item) => {
      if (item.code == code) {
        typeName.push(item.name);
      }
    });
  });
  return typeName;
});
const editForm = reactive({
  alterFileId: "",
  alterReason: "",
  changeChargerName: "",
  changeChargerCode: "",
  changeFeeAuthorize: 0,
  changePlanEndDate: "",
});
//验证延期变更时间
const validateChangePlanEndDate = (rule, value, callback) => {
  if (planEndDate.value) {
    if (new Date(value).getTime() <= new Date(planEndDate.value).getTime()) {
      callback(new Error("延期日期应晚于当前终止日期！"));
    } else {
      callback();
    }
  } else {
    callback();
  }
};
const rules = {
  alterReason: [
    {
      required: true,
      message: "变更原因必填",
    },
  ],
  changeChargerName: [
    {
      required: true,
      message: "变更后负责人必填",
    },
  ],
  changeFeeAuthorize: [
    {
      required: true,
      message: "变更后合同经费必填",
    },
    {
      validator: (rule, value, callback) => {
        if (value == feeAuthorize.value) {
          callback(new Error("变更后合同经费不能与原合同经费相同！"));
        } else {
          callback();
        }
      },
      trigger: "blur",
    },
  ],
  changePlanEndDate: [
    {
      required: true,
      message: "延期终止日期必填",
    },
    { validator: validateChangePlanEndDate, trigger: "blur" },
  ],
};
//获取基础信息
const getBaseInfoData = async () => {
  try {
    const params = {
      proId: projectId.value,
    };
    const res = await baseInfo(params);
    planEndDate.value = res.data.planEndDate;
    chargerCode.value = res.data.chargerCode;
    feeAuthorize.value = res.data.feeAuthorize;
  } catch (error) {
    console.log(error);
  }
};
//获取记录详情
const getDetail = async () => {
  try {
    const res = await recordsDetail(operateId.value);
    detailData.value = res.data;
    const bizProjectAlteration = res.data.bizProjectAlteration;
    checkStatus.value = bizProjectAlteration.checkstatus;
    changeType.value = bizProjectAlteration.alterType.split(",");
    //如果变更证明材料id有值
    if (bizProjectAlteration.alterFileId) {
      fileList.value.push({
        name: bizProjectAlteration.fileName,
        id: bizProjectAlteration.alterFileId,
      });
    }
  } catch (error) {
    console.log(error);
  }
};
// 新增
const add = (proId) => {
  operateId.value = null;
  projectId.value = proId;
  dialogVisible.value = true;
  changeTypeList.value = useCommonFetch("变更类型（横）");
};
//编辑
const edit = async (id, proId, tId, isAudit) => {
  operateId.value = id;
  projectId.value = proId;
  taskId.value = tId;
  isAuditor.value = isAudit;
  dialogVisible.value = true;
  nextTick(async () => {
    await getDetail();
    changeTypeList.value = useCommonFetch("变更类型（横）");
    assignObj(editForm, detailData.value.bizProjectAlteration);
  });
};
defineExpose({ add, edit });
//变更类型改变
const typeChange = (val) => {
  if (!val.length) {
    changeTypeList.value.value.forEach((item) => {
      item.disabled = false;
    });
  } else {
    if (val.includes("middleStop")) {
      changeTypeList.value.value.forEach((item) => {
        if (item.code != "middleStop") {
          item.disabled = true;
        }
      });
    } else {
      changeTypeList.value.value.forEach((item) => {
        if (item.code == "middleStop") {
          item.disabled = true;
        }
      });
    }
  }
};
//根据姓名查询负责人
const queryChargerPerosn = async (queryString, cb) => {
  if (queryString.trim() == "") {
    return;
  }
  editForm.changeChargerCode = "";
  const params = {
    name: queryString,
  };
  try {
    const res = await getPersonList(params);
    cb(res.data);
  } catch (error) {
    console.log(error);
  }
};
//选择负责人
const selectChargerPerosn = (val) => {
  //判断选择的变更后负责人是否是原负责人
  if (val.id == chargerCode.value) {
    ElMessage({
      message: "变更后负责人不能是项目原负责人！",
      type: "error",
    });
    editForm.changeChargerName = "";
    editForm.changeChargerCode = "";
    return;
  }
  editForm.changeChargerCode = val.id;
};
//选择负责人框失去焦点
const chargerPerosnBlur = () => {
  if (!editForm.changeChargerCode) {
    editForm.changeChargerName = "";
    editForm.changeChargerCode = "";
  }
};
const emit = defineEmits(["save-success"]);
//保存
const save = async (type) => {
  try {
    submitType.value = type;
    await editFormRef.value?.validate(async (valid) => {
      if (valid) {
        //判断是否选择了变更类型
        if (!changeType.value.length) {
          ElMessage({
            message: "请选择变更类型！",
            type: "error",
          });
          return;
        }
        //根据选择的变更类型 清空未选择的变更类型的值 chargerName  feeAuthorize delayFinish middleStop
        if (!changeType.value.includes("chargerName")) {
          editForm.changeChargerName = "";
          editForm.changeChargerCode = "";
        }
        if (!changeType.value.includes("feeAuthorize")) {
          editForm.changeFeeAuthorize = "";
        }
        if (!changeType.value.includes("delayFinish")) {
          editForm.changePlanEndDate = "";
        }
        const params = {
          baseInfos: {
            projectId: projectId.value,
            classId: "yfContract",
            alterType: changeType.value.join(","),
            alterTypeName: changeTypeName.value.join(","),
            ...editForm,
            submitType: type,
            isAuditor: isAuditor.value,
            taskId: taskId.value,
            checkstatus: checkStatus.value,
          },
        };
        if (operateId.value) {
          params.baseInfos.id = operateId.value;
        }
        loading.value = true;
        const res = await addRecords(params);
        if (res.code === 200) {
          ElMessage({
            message: "操作成功！",
            type: "success",
          });
          emit("save-success");
          dialogVisible.value = false;
        }
      }
    });
  } catch (error) {
    console.log(error);
  } finally {
    loading.value = false;
  }
};
//上传附件改变
const fileChange = () => {
  const ids = fileList.value.map((item) => {
    const id = item.response ? item.response.data : item.id;
    return id;
  });
  editForm.alterFileId = ids.join(",");
};
const handleOpen = () => {
  getBaseInfoData();
};
const handleClose = () => {
  editFormRef.value.resetFields();
  editForm.changeChargerCode = "";
  changeType.value = [];
  fileList.value = [];
  isAuditor.value = false;
  taskId.value = "";
  checkStatus.value = "";
  loading.value = false;
};
//监听changeTypeList改变
watch(
  () => changeTypeList.value.value,
  () => {
    if (changeTypeList.value.value) {
      typeChange(changeType.value);
    }
  }
);
</script>

<style scoped lang="scss">
@import url("@/views/project/index.scss");
.base-table {
  border-top: 0;
  tr {
    &:first-child {
      td {
        border-top: 0;
      }
    }
  }
}
:deep(.el-dialog__body) {
  padding-bottom: 55px !important; //受父弹框样式影响 需加这一行
}
</style>
